<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="name" label="书名">
				<uni-easyinput placeholder="书籍名称" v-model="formData.name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="author" label="作者">
				<uni-easyinput placeholder="作者" v-model="formData.author"></uni-easyinput>
			</uni-forms-item>
			<!-- <uni-forms-item name="click" label="点击次数">
        <uni-easyinput placeholder="点击次数" type="number" v-model="formData.click"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="source" label="来源">
        <uni-easyinput placeholder="书籍来源" v-model="formData.source"></uni-easyinput>
      </uni-forms-item> -->
			<uni-forms-item name="status" label="状态">
				<uni-easyinput placeholder="书籍状态" v-model="formData.status"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="type" label="类别">
				<picker @change="bindPickerChange" :value="typeIndex" :range="typeList" mode="multiSelector">
					<view class="type-box">{{formData.type?formData.type:'请选择类别'}}</view>
				</picker>
			</uni-forms-item>
			<!-- <uni-forms-item name="updateTime" label="更新时间">
				<uni-easyinput placeholder="书籍更新时间" v-model="formData.updateTime"></uni-easyinput>
			</uni-forms-item> -->
			<!-- <uni-forms-item name="word" label="字数">
        <uni-easyinput placeholder="书籍字数" type="number" v-model="formData.word"></uni-easyinput>
      </uni-forms-item> -->
			<uni-forms-item name="imgUrl" label="封面">
				<view style="display: flex;">
					<image :src="this.formData.imgUrl?this.formData.imgUrl:'/static/up.png'"
						style="width: 60px;height: 80px;cursor: pointer;" @click="updateImage"></image>
				</view>
			</uni-forms-item>
			<uni-forms-item name="synopsis" label="简介">
				<uni-easyinput type="textarea" placeholder="书籍简介" v-model="formData.synopsis"
					:maxlength="-1"></uni-easyinput>
			</uni-forms-item>
			<!-- <uni-forms-item name="list" label="章节目录">
				<view v-for="(item,index) in formData.list" :key="index" class="list">
					<view class="name">
						<uni-easyinput :placeholder="'第'+(index+1)+'章'" v-model="formData.list[index]"
							@change="addList(index)"></uni-easyinput>
					</view>
				</view>
			</uni-forms-item> -->
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/book.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'book';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"name": "",
				"author": "",
				"click": null,
				"source": "",
				"status": "",
				"type": "",
				"updateTime": "",
				"word": null,
				"imgUrl": "",
				"synopsis": "",
				"list": []
			}
			return {
				typeList: [],
				typeIndex: [],
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		onLoad() {
			this.formData.list.push('')
			this.getTypeList()
		},
		methods: {
			updateImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: res => {
						console.log(res)
						var tempFile = res.tempFiles[0];
						var tempFilePath = res.tempFilePaths.shift();
						uni.showLoading({
							mask: true,
							title: '正在上传'
						})
						//进行上传操作
						uniCloud.uploadFile({
							filePath: tempFilePath,
							cloudPath: tempFile.name,
							onUploadProgress: function(progressEvent) {
								var percentCompleted = Math.round(
									(progressEvent.loaded * 100) / progressEvent.total
								);
							},
							success: (res) => {
								uni.hideLoading()
								this.formData.imgUrl = res.fileID;
							},
							fail: (error) => {
								console.log(error)
								uni.hideLoading()
							}
						});
					}
				});
			},
			bindPickerChange(e) {
				this.formData.type = ''
				let indexList = e.detail.value
				for (let i = 0; i < indexList.length; i++) {
					if (indexList[i] != 0) {
						this.formData.type += this.typeList[i][indexList[i]] + ','
					}
				}
				this.formData.type = this.formData.type.slice(0, -1);
				console.log(this.formData.type)
			},
			getTypeList() {
				db.collection('config').field('typeList').get().then((res) => {
					let typeList = res.result.data[0].typeList
					for (let type of typeList) {
						this.typeList.push(['', ...type.list])
						this.typeIndex.push(0)
					}
				})
			},
			/**
			 * 添加章节
			 */
			addList(index) {
				if (index + 1 == this.formData.list.length && this.formData.list[index] != "") {
					this.formData.list.push('')
				}
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				value.list = []
				value.word = 0
				value.source = ''
				value.click = 0
				value.updateTime = ''
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>
<style>
	.name {
		margin-top: 20rpx;
	}

	.type-box {
		width: 100%;
		height: 70rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
		line-height: 70rpx;
		padding-left: 20rpx;
		font-size: 24rpx;
		color: #999;
	}
</style>